package com.manager.gen.module.platform.core.service;

import java.util.*;

import com.manager.commons.Constant;
import com.manager.commons.utils.PinyinUtil;
import com.manager.commons.utils.UUIDUtil;
import com.manager.commons.mybatis.service.GenericService;
import com.manager.gen.module.platform.core.entity.view.PlatformUserRoleView;
import com.manager.gen.module.platform.core.entity.view.SelectView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.manager.commons.encrypt.SHAUtil;
import com.manager.commons.encrypt.md5.MD5;
import com.manager.commons.utils.StringUtil;
import com.manager.commons.base.DataGrid;
import com.manager.commons.mybatis.dao.GenericDao;
import com.manager.gen.module.platform.core.dao.PlatformUserDao;
import com.manager.gen.module.platform.core.entity.PlatformUser;
import com.manager.gen.module.platform.core.entity.view.PlatformUserView;
import com.manager.core.shiro.config.ShiroUtil;
import com.manager.core.web.json.AjaxJson;

/**
 * PlatformUserService
 *
 * @author H
 * @version 1.0
 */
@Service
public class PlatformUserService extends GenericService<PlatformUser> {

    @Autowired
    private PlatformUserDao jdbcDao;

    @Override
    public GenericDao<PlatformUser> getDao() {
        return jdbcDao;
    }

    protected static final Map<String, String> required = new LinkedHashMap<String, String>() {
        {
        }
    };

    public PlatformUserView findView(Map<String, Object> params) {
        return jdbcDao.findView(params);
    }

    public PlatformUserView findAccountView() {
        return jdbcDao.findAccountView(ShiroUtil.currentAccount());
    }

    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    @Override
    public DataGrid queryPage(Map<String, Object> params) {
        if (null != params) {
            int count = jdbcDao.countView(params);
            List<PlatformUserView> list = jdbcDao.queryView(params);
            return new DataGrid(count, list);
        }
        return new DataGrid(0, new ArrayList<PlatformUserView>());
    }

    /**
     * 登录
     *
     * @param account
     * @return
     */
    public PlatformUser login(String account) {
        return jdbcDao.login(new HashMap<String, Object>() {
            private static final long serialVersionUID = -4160187128017253623L;

            {
                put("account", account);
            }
        });
    }

    /**
     * 新增
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson edit(Map<String, Object> params) throws Exception {
        try {
            if (null != params) {
                String msg = check(params, required);
                if (StringUtil.isNotEmpty(msg)) {
                    return new AjaxJson(msg);
                }
                String puId = getParamsString(params, "_id");
                // 根据手机号码查询是否存在
                String puPhone = getParamsString(params, "puPhone");

                int maxJob = 0;
                String name = getParamsString(params, "puName");
                String pinyins = PinyinUtil.toPinyin(name);
                params.put("puPinyin", pinyins);
                String xmzm = PinyinUtil.getFirstLetter(name);
                String account = xmzm + puPhone;
                params.put("puAccount", account);
                boolean isAdd = true;
                //如果id为null则说明是新增，反之则是修改
                if (StringUtil.isEmpty(puId)) {
                    Map<String, Object> checkPhone = jdbcDao.checkPhoneCount(puPhone);
                    maxJob = getParamsInt(checkPhone, "maxJob");
                    if (getParamsInt(checkPhone, "phone") > 0) {
                        return new AjaxJson("手机号码已存在,无法创建用户！");
                    }
                    puId = UUIDUtil.getInstance().getUUID();
                    params.put("_id", puId);
                    // 姓名首字+手机号码后4位，密码两次加密
//                    String pwd = puPhone.substring(5);
//                    String sha256 = SHAUtil.SHA256(pwd);
//                    String puPassword = MD5.md5(sha256);
                    params.put("puPassword", "DD6E5E5918E94D997C686FCEBC56922F");
                } else {
                    isAdd = false;
                }

                params.put("puDataQuery", "-3");
                // 插入用户数据
                int f = 0;
                if (isAdd) {
                    f += jdbcDao.insertMap(params);
                } else {
                    f += jdbcDao.updateMap(params);

                }
                params.put("purId", UUIDUtil.getInstance().getUUID());
                //增加用户编辑记录
                f += jdbcDao.insertUserRecord(params);
                if (f > 0) {
                    if (isAdd) {
                        if (maxJob == 0) maxJob = 1001;
                        params.put("puaJobId", maxJob + 1);
                        f += jdbcDao.insertUserArchive(params);
                    } else {
                        f += jdbcDao.updateUserArchiveMap(params);
                        jdbcDao.deleteUserRole(params);
                    }
                    params.put("purId", UUIDUtil.getInstance().getUUID());
                    params.put("purDefault", 1);
                    f += jdbcDao.insertUserRole(params);
                }

                if (f > 0) {
                    return new AjaxJson(1, "保存成功!");
                } else {
                    throw new Exception();
                }
            }
            return new AjaxJson("参数错误！");
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 重置密码
     *
     * @param params
     * @return
     */
    public AjaxJson updatePwd(Map<String, Object> params) {
        if (null != params) {
            String oldPwd = getParamsString(params, "oldPwd");
            String newPwd = getParamsString(params, "newPwd");
            String opwd = MD5.md5(oldPwd);
            String oldPwdf = jdbcDao.findPwd(params);
            if (!opwd.equals(oldPwdf)) {
                return new AjaxJson(0, "原密码输入错误");
            }
            String npwd = MD5.md5(newPwd);
            params.put("pwd", npwd);
            int f = jdbcDao.updatePwd(params);
            return new AjaxJson(f, "密码修改" + ((f > 0) ? "成功" : "失败！"));
        }
        return new AjaxJson("参数错误");
    }

    /**
     * 重置密码
     *
     * @param params
     * @return
     */
    public AjaxJson resetPwd(Map<String, Object> params) {
        if (null != params) {
            String puId = getParamsString(params, "_id");
            if (StringUtil.isNotEmpty(puId)) {
               // PlatformUserView platformUserView = jdbcDao.findView(params);
//                String pwd = platformUserView.getPuPhone().substring(5);
//                String sha256 = SHAUtil.SHA256(pwd);
//                String puPassword = MD5.md5(sha256);
                params.put("pwd", "DD6E5E5918E94D997C686FCEBC56922F");
                int f = jdbcDao.resetPwd(params);
                return new AjaxJson(f, "重置" + ((f > 0) ? "成功" : "失败！"));
            }
            return new AjaxJson("用户有误！");
        }
        return new AjaxJson("参数错误");
    }

    /**
     * 查询用户角色
     *
     * @param map
     * @return
     */
    public AjaxJson queryRolesByUser(Map<String, Object> map) {
        map.put("_status", Constant.DbStatus.ENABLE.getEcode());
        List<PlatformUserRoleView> roles = jdbcDao.queryRolesByUser(map);
        return new AjaxJson(1, "", new HashMap<String, Object>() {
            {
                put("roles", roles);
                put("puId", map.get("puId"));
            }
        });
    }

    /**
     * 查询用户角色
     *
     * @return
     */
    public AjaxJson queryAllRole() {
        List<SelectView> roles = jdbcDao.queryAllRole();
        return new AjaxJson(1, "获取成功", roles);
    }

    /**
     *
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson saveRole(Map<String, Object> map) {
        if (null != map) {
            String puId = String.valueOf(map.get("puId"));
            if (StringUtil.isNotEmpty(puId)) {
                int f = jdbcDao.deleteUserRole(map);
                if (f >= 0) {
                    String code = String.valueOf(map.get("prCodes"));
                    map.put("purId", UUIDUtil.getInstance().getUUID());
                    map.put("prCode", code);
                    map.put("purDefault", 0);
                    f = jdbcDao.insertUserRole(map);
                    return new AjaxJson(f);
                }
            }
            return new AjaxJson("puId错误");
        }
        return new AjaxJson("参数错误");
    }

    public List<PlatformUser> queryAll() {
        return jdbcDao.queryAll();
    }
}